<template>
  <div class="goods-detail">
    <myheader outerTitle="商品详情"></myheader>
    <mt-swipe class="swiperbox">
      <mt-swipe-item v-for="(item,index) in thumImags" :key="index">
        <img :src="item.src" alt="轮播图">
        </mt-swipe-item>
    </mt-swipe>
    <div>
      <h4 class="goods-title">{{detailList.title}}</h4>
      <p class="goods-price">
        <span class="market-price">{{detailList.market_price}}</span>
        <span class="sell-price">{{detailList.sell_price}}</span>
      </p>
    </div>
    <div class="goods-info">
      <h4 class="goods-desc">商品参数</h4>
      <p>商品编号：{{detailList.goods_no}}</p>
      <p>库存:{{detailList.stock_quantity}}</p>
      <p>上架时间:{{detailList.add_time |filterTime}}</p>
    </div>
    <mt-button type="primary" size="large" @click="jumpTo('goodsDesc')">图文介绍</mt-button>
    <mt-button type="danger" size="large" @click="jumpTo('goodsComment')">商品评论</mt-button>
    <div class="goods-footer">
      <div class="goods-footer-item contact"><span class="iconfont icon-kefu"></span><span>联系客服</span></div>
      <div class="goods-footer-item cart">
        <span class="iconfont icon-gouwuche"></span>
        <span>购物车</span>
        <span class="badge">{{$store.state.c.totalNum}}</span>
      </div>
      <div class="goods-footer-item add" @click="handleCart"><span>加入购物车</span></div>
      <div class="goods-footer-item buy" @click="jumpTo('cart')"><span>立即购买</span></div>
    </div>
  </div>
</template>
<script>
import myheader from '@/components/myheader'
import { getGoodsDesc, getImgDetail, getCartDate } from '@/api'
export default {
  data () {
    return {
      detailList: {},
      thumImags: [], // 用来存储轮播图的图片
      id: this.$route.params.id,
      cartListPage: [] // 用来存储localStorage中的数据,方便计算属性来获取数量
    }
  },
  components: {
    myheader
  },
  // 当数据挂载上去在初始化，因为要在购买页面执行后再执行，这样购物车的商品数量就可以更新了
  mounted () {
    this.initGoodsDesc()
    // 轮播图初始化
    this.initSwipe()
    // 页面一加载时就获取localStorage中的数据
    this.cartListPage = JSON.parse(localStorage.getItem('cartList') || '[]')
    this.$store.commit('initTotalNum')
  },
  methods: {
    initGoodsDesc () {
      getGoodsDesc(this.id)
        .then(res => {
          // console.log(res)
          this.detailList = res.message[0]
        })
    },
    // 获取轮播图的方法
    initSwipe () {
      getImgDetail(this.id)
        .then(res => {
        // console.log(res)
          this.thumImags = res.message
        })
    },
    // 跳转页面
    jumpTo (urlName) {
      this.$router.push({ name: urlName, params: { id: this.id } })
    },
    // 添加到购物车的操作
    handleCart () {
      // 判断本地是否存储有该商品,先获取loclstorage,假设存储的名称为cartList
      // 1.如果没有就返回一个空数组，方便后面存储数据，将返回的字符转换成对象
      let cartList = JSON.parse(localStorage.getItem('cartList') || '[]')
      // 2.判断该商品在cartList是否存在，根据localStorage的id和当前的id是否相等
      // 使用es6的findIndex进行遍历，存在就返回索引，不存在就返回-1
      let index = cartList.findIndex(item => item.id === parseInt(this.id))
      // 该商品不存在，则创建一个对象来存储商品的信息
      if (index === -1) {
        // 发送请求
        getCartDate(this.id)
          .then(res => {
          // console.log(res);
            let goodsObj = {
              selectState: true, // 默认选中
              id: res.message[0].id,
              title: res.message[0].title,
              img: res.message[0].thumb_path,
              price: this.detailList.sell_price,
              num: 1 // 新增数量为1
            }
            // 将数据push到cartList数组中
            cartList.push(goodsObj)
            // 更改购物车页面中的数据
            this.cartListPage.push(goodsObj)
            this.$store.commit('addTotalNum')
            // 更改本地存储购物车的数据,转换成json格式的字符串才能存入
            localStorage.setItem('cartList', JSON.stringify(cartList))
          })
      } else {
        // 找到了就给当前那一页的num+1
        cartList[index].num += 1
        this.cartListPage[index].num += 1
        this.$store.commit('addTotalNum')
        localStorage.setItem('cartList', JSON.stringify(cartList))
      }
    }
  },
  computed: {
    totalNum () {
      // 定义购物车商品的数量
      let total = 0
      // 循环遍历cartListPage中的num
      this.cartListPage.map(item => {
        total += item.num
      })
      return total
    }
  }
}
</script>

<style lang="scss" scoped>
  .goods-detail {
  margin-bottom: 50px;
  padding: 0 10px;
}
.swiperbox {
  height: 300px;
  img {
    width: 100%;
  }
}

.goods-title {
  font-size: 16px;
  font-weight: bold;
  margin: 10px 0;
}
.goods-price {
  font-size: 14px;
  .market-price {
    text-decoration: line-through;
  }
  .sell-price {
    color: #e4393c;
  }
}

.goods-info {
  font-size: 14px;
   .goods-desc {
    margin-top: 10px;
    font-size: 16px;
    font-weight: bold;
  }
}

.goods-footer {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  height: 50px;
  width: 100%;
  border-top: 1px solid #e7e7e7;
  background-color: #fff;
  .goods-footer-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .contact, .cart {
    width: 40%;
    font-size: 12px;
    position: relative;
  }
  .badge {
    position: absolute;
    top: 3%;
    left: 50%;
    width: 14px;
    height: 14px;
    border-radius: 7px;
    background-color: #e4393c;
    text-align: center;
    line-height: 14px;
    color: white;
  }
  .add, .buy {
    width: 60%;
    color: white;
    &>span {
      font-size: 20px;
    }
  }
  .add {
    background-color: #ff9600;
  }
  .buy {
    background-color: #e4393c;
  }
}
</style>
